<template>
  <fs-page>
    <fs-crud ref="crudRef" v-bind="crudBinding">
      <template #actionbar-left>
        <el-upload ref="upload" :headers="headers" :on-success="handleSuccess" action="/api/file-sys/upload" :limit="1">
          <el-button type="primary">上传</el-button>
        </el-upload>
      </template>
      <template #toolbar-left>
        <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
      </template>
    </fs-crud>
  </fs-page>
</template>

<script lang="ts" setup>
import type { UploadInstance } from 'element-plus'
import { useFs, useFsRef, useExpose } from '@fast-crud/fast-crud'
import createCrudOptions from './crud'
import { getLocal } from '@/lib/utils'
import { useTemplateRef } from 'vue'
import { batchDelete } from './api'
const token = getLocal('token')
const headers = {
  Authorization: `Bearer ${token}`,
}
const { crudRef, crudBinding, context, crudExpose } = useFsRef()
useFs({ crudRef, crudBinding, crudExpose, context, createCrudOptions })
const { selectedIds } = context
onMounted(() => {
  crudExpose.doRefresh()
})

// const upload = useTemplateRef('upload')
const upload = ref<UploadInstance>()
const handleSuccess = () => {
  crudExpose.doRefresh()
  ElMessage.success('上传成功')
  if (!upload.value) return
  upload.value.clearFiles()
}
const handleBatchDelete = async () => {
  if (selectedIds.value?.length > 0) {
    await ElMessageBox.confirm(`确定要批量删除这${selectedIds.value.length}条记录吗`, '确认')
    await batchDelete({ ids: selectedIds.value })
    ElMessage.info('删除成功')
    selectedIds.value = []
    await crudExpose.doRefresh()
  } else {
    ElMessage.error('请先勾选记录')
  }
}
</script>
